<?php

namespace app\api\controller;

use app\api\model\Cart as CartModel;
use app\api\model\Order as OrderModel;
use app\api\model\UserCoupon as UserCouponModel;
use app\api\service\order\Checkout as CheckoutModel;
use app\api\validate\order\Checkout as CheckoutValidate;
use app\common\library\MysicLog;
use Throwable;
/**
 * 订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    protected $user;

    /* @var CheckoutValidate $validate */
    protected $validate;
    /* @var MysicLog $log */
    protected $log;
    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        // 用户信息
        $this->user = $this->getUser();
        // 验证类
        $this->validate = new CheckoutValidate;
        $this->log = MysicLog::instance();
    }

    /**
     * 订单确认-立即购买
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function buyNow()
    {
        $this->log->setFilename('prepay/buynow');

        try{
            // 实例化结算台服务
            $Checkout = new CheckoutModel;
            // 订单结算api参数
            $params = $Checkout->setParam($this->getParam([
                'goods_id' => 0,
                'goods_num' => 0,
                'goods_sku_id' => '',
            ]));

            // 表单验证
            if (!$this->validate->scene('buyNow')->check($params)) {
                $this->log->error($this->validate->getError(), '表单验证失败');
                return $this->renderError($this->validate->getError());
            }

            // 立即购买：获取订单商品列表
            $model = new OrderModel;
            $goodsList = $model->getOrderGoodsListByNow(
                $params['goods_id'],
                $params['goods_sku_id'],
                $params['goods_num']
            );
            // 获取订单确认信息
            $orderInfo = $Checkout->onCheckout($this->user, $goodsList);


            if(bccomp($orderInfo['order_pay_price'], '5000', 2) == 1) {
                return $this->renderError('支付金额不能大于5000元');
            }

            if ($this->request->isGet()) {
                return $this->renderSuccess($orderInfo);
            }
            $this->log->info('', '-----------------------------------------------------------------');
            $this->log->info('开始', '预下单');
            $this->log->info($params, '订单结算请求参数');
            $this->log->info(count($orderInfo['goods_list']), '即将创建的订单个数');
            $this->log->info('开始', '订单结算');
            // 订单结算提交
            if ($Checkout->hasError()) {
                $this->log->error($Checkout->getError(), '订单结算提交错误');
                return $this->renderError($Checkout->getError());
            }
            $this->log->info('完成', '订单结算提交');
            // 创建订单
            $this->log->info('开始', '创建订单');
            if (!$Checkout->createOrder($orderInfo)) {
                $this->log->error($Checkout->getError(), '订单创建失败');
                return $this->renderError($Checkout->getError() ?: '订单创建失败');
            }
            $this->log->info($Checkout->model['order_no'], '订单编号');
            $this->log->info('结束', '创建订单');

            $this->log->info('开始', '构建微信支付请求');
            // 构建微信支付请求
            $payment = $model->onOrderPayment($this->user, $Checkout->model, $params['pay_type']);
            $this->log->info([
                'order_id' => $Checkout->model['order_id'],   // 订单id
                'pay_type' => $params['pay_type'],  // 支付方式
                'payment' => $payment               // 微信支付参数
            ], '构建微信支付请求');
            $this->log->info('结束', '返回微信预支付信息到前端');
            $this->log->info('结束', '预下单');
            // 返回结算信息
            return $this->renderSuccess([
                'order_id' => $Checkout->model['order_id'],   // 订单id
                'pay_type' => $params['pay_type'],  // 支付方式
                'payment' => $payment               // 微信支付参数
            ], ['success' => '支付成功', 'error' => '订单未支付']);
        } catch(Throwable $t){
            $this->log->error(
                ['msg' => $t->getMessage(), 'file' => $t->getFile(), 'line' => $t->getLine(), 'code' => $t->getCode()],
                'buyNow抛出异常');
            return $this->renderError($t->getMessage());
        }

    }

    /**
     * 当面付支付
     * @param $price
     * @param $couponId
     * @param $message
     * @param $discount
     * @param $pay_way
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function payFace($price,$couponId,$message,$discount,$pay_way,$dis_type){
        if(bccomp($price, '5000', 2) == 1) {
            return $this->renderError('当面付金额不能大于5000元');
        }
        $this->log->setFilename('prepay/payface');
        $this->log->info('', '-----------------------------------------------------------------');
        $this->log->info('开始', '预下单');

        try{
            // 实例化结算台服务
            // 立即购买：获取订单商品列表
            $model = new OrderModel;
            $orderInfo=[
                'user_id'=>$this->user['user_id'],
                'order_total_price'=>$price,
                'order_price'=>$price,
                'remark'=>$message,
                'pay_type'=>$pay_way,
                'dis_type'=>$dis_type,
            ];
            if ($dis_type==1){
                $orderInfo['coupon_id']=$couponId;
                $orderInfo['coupon_money']=$discount;
                $orderInfo['order_pay_price']=bcsub($price,$discount,2);
                $orderInfo['balance_money']=0;
                $orderInfo['balance_num']=0;
            }elseif($dis_type==2){
                $orderInfo['coupon_money']=0;
                $orderInfo['coupon_id']=0;
                $orderInfo['balance_money']=$discount;
                $orderInfo['balance_num']  =$discount;
                // 余额支付标记订单已支付
                $orderInfo['order_pay_price']=bcsub($price,$discount,2);
            }
            if($pay_way==10){
                if ($this->user['money'] < $price) {
                    return $this->renderError('用户余额不足，无法使用余额支付');
                }
            }
            $this->log->info($orderInfo, '订单信息');
            $this->log->info('开始', '创建订单');
            // 创建订单
            if (!$model->createOrder($orderInfo)) {
                $this->log->info($model->getError(), '创建订单失败');
                return $this->renderError($model->getError() ?: '订单创建失败');
            }
            $this->log->info('成功', '创建订单');
            // 构建微信支付请求
            $payment = $model->onOrderPayment($this->user, $model ,$pay_way);
            $this->log->info('结束', '返回微信预支付信息到前端');
            $this->log->info('结束', '预下单');
            // 返回结算信息
            return $this->renderSuccess([
                'order_id' => $model['order_id'],   // 订单id
                'pay_type' =>$pay_way,  // 支付方式
                'payment' => $payment               // 微信支付参数
            ], ['success' => '支付成功', 'error' => '订单未支付']);
        }catch(\Throwable $t) {
            $this->log->error(
                ['msg' => $t->getMessage(), 'file' => $t->getFile(), 'line' => $t->getLine(), 'code' => $t->getCode()],
                'payFace抛出异常');
            return $this->renderError();
        }


    }

    /**
     * 订单确认-购物车结算
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function cart()
    {
        // 实例化结算台服务
        $Checkout = new CheckoutModel;
        // 订单结算api参数
        $params = $Checkout->setParam($this->getParam([
            'cart_ids' => '',
        ]));
        // 商品结算信息
        $CartModel = new CartModel($this->user);
        // 购物车商品列表
        $goodsList = $CartModel->getList($params['cart_ids']);
        // 获取订单结算信息
        $orderInfo = $Checkout->onCheckout($this->user, $goodsList);

        if(bccomp($orderInfo['order_pay_price'], '5000', 2) == 1) {
            return $this->renderError('支付金额不能大于5000元');
        }
        if ($this->request->isGet()) {
            return $this->renderSuccess($orderInfo);
        }
        // 创建订单
        if (!$Checkout->createOrder($orderInfo)) {
            return $this->renderError($Checkout->getError() ?: '订单创建失败');
        }
        // 移出购物车中已下单的商品
        $CartModel->clearAll($params['cart_ids']);
        // 构建微信支付请求
        $payment = $Checkout->onOrderPayment();
        // 返回状态
        return $this->renderSuccess([
            'order_id' => $Checkout->model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
            'payment' => $payment               // 微信支付参数
        ], ['success' => '支付成功', 'error' => '订单未支付']);
    }

    /**
     * 订单结算提交的参数
     * @param array $define
     * @return array
     */
    private function getParam($define = [])
    {
        return array_merge($define, $this->request->param());
    }

    /**
     * 选择优惠券优惠
     * @param $price
     * @param $couponId
     * @return array
     */
    public function coupon($price,$couponId){
        if($couponId==0){
            return $this->renderSuccess(0,'优惠金额');
        }
        $coupon=UserCouponModel::getCouponType($this->user['user_id'],$couponId);
        if($coupon['coupon_type']['value']==10){
          $disc=$coupon['reduce_price'];
          $payPrice=bcsub($price,$disc,2);
        }else{
            $disc= bcmul($price,(1-($coupon['discount']/10)),2);
            $payPrice=bcsub($price,$disc,2);
        }
        $data=['payPrice'=>$payPrice,'dis'=>$disc];
        return $this->renderSuccess( $data,'优惠金额');
    }

    /**
     * 选择零钱优惠
     * @param $price
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function balance($price){
        $user=$this->getUser();
        $wxappId=$user['wxapp_id'];
        $moneypercent=db('wxapp_setting')->where('wxapp_id',$wxappId)->value('moneypercent');
        if($moneypercent==0){
            $disc=0;
            $payPrice=$price;
        }else{
            //将支付金额转化成等额可使用零钱额
            $prices=bcmul($price,($moneypercent/100),2);
            //用户零钱
            $balance=$user['balance'];
            //如果支付金额大于零钱金额
            if($prices>=$balance){
                $disc=$balance;
                $payPrice=bcsub($price,$disc,2);
            }else{
                $disc=$prices;
                $payPrice=bcsub($price,$disc,2);
            }
        }
        $data=['payPrice'=>$payPrice,'dis'=>$disc];
        return $this->renderSuccess( $data,'优惠金额');
    }

    /*
     * 判断面对面支付时是否显示零钱抵扣
     */
    public function checkFaceView(){
        $user=$this->getUser();
        $wxappId=$user['wxapp_id'];
        $moneypercent=db('wxapp_setting')->where('wxapp_id',$wxappId)->find();
        if($moneypercent){
            if($moneypercent['moneypercentstatus']==1){
                //return json_encode(['code'=>-2,'msg'=>'不用显示零钱开关项目']);
                return $this->renderSuccess( ['isShow'=>true],'可以显示');
            }
            return $this->renderSuccess( ['isShow'=>false],'不用显示零钱开关项目');
        }else{
            return $this->renderSuccess( ['isShow'=>false],'未获取到配置信息');
        }
    }


}
